package com.robusta.cityuate.fragments;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.robusta.cityuate.R;
import com.robusta.cityuate.activities.OfferingCreateEditActivity;
import com.robusta.cityuate.activities.OfferingPofileActivity;
import com.robusta.cityuate.adapters.OfferingsListAdapter;
import com.robusta.cityuate.base.CityuateListFragment;
import com.robusta.cityuate.base.ViewType;
import com.robusta.cityuate.objects.Offering;
import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.GetSpotService;
import com.robusta.cityuate.utils.ConnectionUtils;

public class OfferingsListFragment extends CityuateListFragment {

	private String TAG = OfferingsListFragment.class.getName();
	public String DEL_TAG;
	private OfferingsListAdapter adapter;
	ViewType.Type ownershipType;

	public interface SpotCarrier {
		public Spot getSpot();

		public ViewType.Type getOwnershipType();

		public void setSpot(Spot spot);
	}

	private CityuateBroadCastReceiver receiver = new CityuateBroadCastReceiver() {
		@Override
		public void onSuccess() {
			getOfferingsSuccess();
		}

		@Override
		public void onFailure() {
			getOfferingsFail();
		}

		@Override
		public void onCancel() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					false);
			ConnectionUtils.clearConnection(mContext, TAG);
		}
	};

	private CityuateBroadCastReceiver deleteReceiver = new CityuateBroadCastReceiver() {

		@Override
		public void onCancel() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					false);
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

		@Override
		public void onSuccess() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					false);
			Toast.makeText(mContext, getString(R.string.offering_deleted),
					Toast.LENGTH_LONG).show();
			getOfferings();
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

		@Override
		public void onFailure() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					false);
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, DEL_TAG),
					Toast.LENGTH_LONG).show();
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

	};
	private Button retryBtn;
	private ProgressBar progressBar;
	private LinearLayout listPart;
	private LinearLayout fragmentView;
	private Spot spot;

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		registerForContextMenu(getListView());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		fragmentView = (LinearLayout) inflater.inflate(
				R.layout.offerings_list_fragment_view, container, false);
		progressBar = (ProgressBar) fragmentView
				.findViewById(R.id.spots_loading);
		listPart = (LinearLayout) fragmentView.findViewById(R.id.list_part);
		// show retry button
		retryBtn = (Button) fragmentView.findViewById(R.id.retry);

		retryBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// fragmentView.removeView(retryBtn);
				retryBtn.setVisibility(View.GONE);
				ConnectionUtils.clearConnection(mContext, TAG);
				getOfferings();

			}
		});

		return fragmentView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		this.ownershipType = ((SpotCarrier) getActivity()).getOwnershipType();
		this.adapter = new OfferingsListAdapter(mContext, ownershipType);
		setListAdapter(adapter);
		this.spot = ((SpotCarrier) getActivity()).getSpot();

		TAG += ("_" + spot.getId());
		DEL_TAG = TAG + "_DEL";

	}

	@Override
	public void onResume() {
		super.onResume();

		// register receiver
		mContext.registerReceiver(receiver, new IntentFilter(TAG));
		mContext.registerReceiver(deleteReceiver, new IntentFilter(DEL_TAG));

		Log.d(TAG, "onResume");
		if (ConnectionUtils.isConnecting(mContext, TAG)) {
			progressBar.setVisibility(View.VISIBLE);
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
		} else if (ConnectionUtils.wasConnected(mContext, TAG))
			if (ConnectionUtils.isResultSuccessful(mContext, TAG))
				getOfferingsSuccess();
			else
				getOfferingsFail();
		else
			getOfferings();

		if (ConnectionUtils.isConnecting(mContext, DEL_TAG)) {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
		} else if (ConnectionUtils.wasConnected(mContext, DEL_TAG))
			if (ConnectionUtils.isResultSuccessful(mContext, DEL_TAG))
				deleteReceiver.onSuccess();
			else
				deleteReceiver.onFailure();
	}

	@Override
	public void onPause() {
		super.onPause();
		mContext.unregisterReceiver(receiver);
		mContext.unregisterReceiver(deleteReceiver);

		if (!ConnectionUtils.isConnecting(mContext, DEL_TAG))
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.e(TAG, "Oferring List OnDestroy");
		// if (!ConnectionUtils.isConnecting(mContext, TAG))
		ConnectionUtils.clearConnection(mContext, TAG);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		android.view.MenuInflater inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.offerings_context_menu, menu);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		if (!spot.isCreator()) {
			menu.removeItem(R.id.delete);
			menu.removeItem(R.id.edit);
		} else if (((Offering) adapter.getItem(info.position)).hasReservation())
			menu.removeItem(R.id.edit);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		Offering offer = (Offering) adapter.getItem(info.position);
		switch (item.getItemId()) {
		case R.id.delete:
			confirmDeleteOffering(offer);
			break;
		case R.id.edit:
			Intent edit = new Intent(mContext, OfferingCreateEditActivity.class);
			edit.putExtra(OfferingCreateEditActivity.IS_EDIT, true);
			edit.putExtra(Offering.OFFERING, offer);
			startActivityForResult(edit,
					OfferingCreateEditActivity.OFFER_CREATEEDIT_CODE);
			break;
		}
		return super.onContextItemSelected(item);
	}

	/**
	 * confirm delete spot if ok delete it
	 */
	public void confirmDeleteOffering(final Offering offer) {
		// Use the Builder class for convenient dialog construction

		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(getString(R.string.delete_confirm) + " "
				+ offer.getName());
		builder.setMessage(R.string.offering_delete_confirm_msg_single)
				.setPositiveButton(R.string.delete,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								getSherlockActivity()
										.setSupportProgressBarIndeterminateVisibility(
												true);
								offer.delete(mContext, DEL_TAG);
							}
						}).setNegativeButton(R.string.cancel, null);

		builder.show();
	}

	/**
	 * fire service to get offerings
	 * 
	 */
	public void getOfferings() {
		Log.d(TAG, "getOfferings");
		if (!ConnectionUtils.isNetworkAvailable(mContext))
			ConnectionUtils.showNoConnectionDialog(mContext);
		getSherlockActivity()
				.setSupportProgressBarIndeterminateVisibility(true);
		listPart.setVisibility(View.GONE);
		retryBtn.setVisibility(View.GONE);
		progressBar.setVisibility(View.VISIBLE);
		Intent backgroud_regService = new Intent(mContext, GetSpotService.class);
		backgroud_regService.setAction(TAG);
		backgroud_regService.putExtra(GetSpotService.WITH_OFFERINGS, true);
		backgroud_regService.putExtra(GetSpotService.LOGIN_RQUIRED, true);
		backgroud_regService.putExtra(Spot.SPOT_ID, spot.getId());
		mContext.startService(backgroud_regService);
		Log.e(TAG, "Spot Offerings fired");
	}

	/**
	 * success getting offers
	 */
	private void getOfferingsSuccess() {
		getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
				false);
		listPart.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.GONE);

		String josnSpotString = ConnectionUtils.getExtra(mContext, TAG);

		if (josnSpotString == null) {
			Log.e(TAG, "emptylist");
			return;
		}
		try {
			spot = Spot.createFromJSON(new JSONObject(josnSpotString));
			adapter.upDateEntries(spot.getOfferings());
			((SpotCarrier) getActivity()).setSpot(spot);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * fail getting offers
	 */
	private void getOfferingsFail() {
		getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
				false);
		progressBar.setVisibility(View.GONE);
		retryBtn.setVisibility(View.VISIBLE);

		Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, TAG),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, TAG);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent timeSlots = new Intent(mContext, OfferingPofileActivity.class);
		timeSlots.putExtra(Offering.OFFERING, (Offering) l.getAdapter()
				.getItem(position));
		timeSlots.putExtra(ViewType.VIEWTYPE,ownershipType );
		getActivity().startActivityForResult(timeSlots,
				OfferingPofileActivity.SHOW_OFFER_CODE);
	}

}
